//
//  DSYPlayerTool.m
//  BLDMusics
//
//  Created by dllo on 16/3/23.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "DSYPlayerTool.h"


@interface DSYPlayerTool ()

@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, retain) NSTimer *timer;

@end


@implementation DSYPlayerTool

+ (instancetype)sharePlayerTool
{
    static DSYPlayerTool *playerTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        playerTool = [[DSYPlayerTool alloc] init];
    });
    return playerTool;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        // 监听播放完毕
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didToStop) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

- (void)didToStop {
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(didStop)]) {
        [self.delegate didStop];
    }
}

/**
 * 根据网址进行音乐播放
 */
- (void)playWithUrl:(NSString *)urlStr
{
    // 创建item对象
    NSURL *url = [NSURL URLWithString:urlStr];
    
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    
    // 切换到当前的音乐即可
    [self.player replaceCurrentItemWithPlayerItem:_playerItem];
    // 添加观察者，监听专题太
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        // 正常
        if (self.player.status == AVPlayerStatusReadyToPlay) {
            [self play];
        }
        if (self.player.status == AVPlayerStatusFailed) {
            [self.delegate didStop];
        }
        if (self.player.status == AVPlayerStatusUnknown) {
            [self.delegate didStop];
        }
    }
}

- (void)play {
    if (_isPlaying == YES) {
        return;
    }
    [self.player play];
    _isPlaying = YES;
    
    if (self.timer != nil) {
        return;
    }
    
    // 开启定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

- (void)pause {
    if (_isPlaying == NO) {
        return;
    }
    
    [self.player pause];
    self.isPlaying = NO;
    
    // 停掉定时器
    [self.timer invalidate];
    self.timer = nil;
}

- (void)timerAction {
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(playingWithTime:)]) {
        // 计算当前的秒数
        
        // 获取总的视频时间
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        // 获取视频的当前时间
        CGFloat current = CMTimeGetSeconds(self.playerItem.currentTime);
        
        self.duration = duration;
        self.current = current;
        
        [self.delegate playingWithTime:current / duration];
    }
}

// 从指定时间开始播放
- (void)seekToTime:(NSTimeInterval)time
{
    // 先暂停
    [self pause];
    
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
       // 完成后即将开始播放
        [self play];
    }];
}

- (void)setSound:(CGFloat)sound
{
    self.player.volume = sound;
}

- (CGFloat)sound {
    return self.player.volume;
}

#pragma mark - 懒加载
- (AVPlayer *)player
{
    if (!_player) {
        self.player = [[AVPlayer alloc] init];
    }
    return _player;
}

- (CGFloat)duration
{
    return CMTimeGetSeconds(self.playerItem.duration);
}

- (CGFloat)current
{
    return CMTimeGetSeconds(self.playerItem.currentTime);
}

#pragma mark - 本地音乐的播放
- (void)playWithLocalStr:(NSString *)urlStr
{
    
    // 1. 获取沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2. 拼接路径
    NSString *songsPath = [documentPath stringByAppendingPathComponent:@"songs"];
    // 3. 歌曲文件路径
    NSString *url = [songsPath stringByAppendingPathComponent:urlStr];
    
    NSURL *sourceMovieUrl = [NSURL fileURLWithPath:url];
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieUrl options:nil];
    
    self.playerItem = [[AVPlayerItem alloc] initWithAsset:movieAsset];

    
    // 切换到到当前的音乐即可
    [self.player replaceCurrentItemWithPlayerItem:_playerItem];
    // 添加观察者，监听状态
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
}


@end
